<?php

namespace My\Model;

use Utuo\UtuoModel;

class MallOrderModel extends UtuoModel {
	
	/* 订单状态 */
	const ORDER_STATUS_INVALID = 0; // 订单异常
	const ORDER_STATUS_CANCELED = 1; // 已取消
	const ORDER_STATUS_PAY = 2;  // 待支付
	const ORDER_STATUS_SHIPPING = 3; // 待发货
	const ORDER_STATUS_SIGN = 4; // 待签收
	const ORDER_STATUS_COMPLETED = 5; // 交易成功
	const ORDER_STATUS_RETURN_APPLY = 6; // 已申请退货
	const ORDER_STATUS_RETURN_REFUSED = 7; // 拒绝退货
	const ORDER_STATUS_RETURN_PROCESSING = 8; // 退货中
	const ORDER_STATUS_RETURN_SUCCESS = 9; // 退货成功
	const ORDER_STATUS_REFUND_APPLY = 10; // 已申请退全款
	const ORDER_STATUS_REFUND_PROCESSING = 11; // 退款处理中
	const ORDER_STATUS_REFUND_SUCCESS = 12; // 退款成功
	const ORDER_STATUS_REFUND_FAIL = 13; // 退款失败
	
	/* 订单送礼状态 */
	const ORDER_GIFTS_STATUS_SAVED = 0; // 已下单
	const ORDER_GIFTS_STATUS_SHARING = 1; // 分享阶段
	const ORDER_GIFTS_STATUS_CONSIGNEE = 2; // 已抢走
	
	/* 订单送礼状态 */
	const ORDER_COQUETRY_STATUS_SAVED = 0; // 已下单
	const ORDER_COQUETRY_STATUS_SHARING = 1; // 分享阶段
	const ORDER_COQUETRY_STATUS_CONSIGNEE = 2; // 代付完成
	const ORDER_COQUETRY_STATUS_FAIL = 3; // 代付失败已结束
	
	/* 付款状态 */
	const PAY_STATUS_NOT_PAID = 0; // 待支付
	const PAY_STATUS_PAID = 1; // 已支付
	const PAY_STATUS_REFUND = 2; // 已退款
	
	/* 购买方式 */
	const BUY_METHOD_COMMON = 0; // 普通
	const BUY_METHOD_GIFTS = 1; // 送礼
	const BUY_METHOD_COQUETRY = 2; // 撒娇
	const BUY_METHOD_TRY = 3; // 试用
	
	/* 订单的退款状态 */
	const ORDER_REFUND_STATUS_NAR = 0; // 非退款订单
	const ORDER_REFUND_STATUS_ON = 1; // 订单中存在退款中的商品
	const ORDER_REFUND_STATUS_FINISH = 2; // 订单中所有退款已完成
	
	/* 退款状态 */
	const REFUND_STATUS_UNREAD = 0; // 待处理
	const REFUND_STATUS_AGREE = 1; // 同意退款
	const REFUND_STATUS_REJECT = 2; // 退款已驳回
	const REFUND_STATUS_BACK= 3; // 已退回
	const REFUND_STATUS_FAIL= 4; // 退回失败
		
	// 购物状态
	private $status = array(
			0 => '订单异常',
			1 => '已取消',
			2 => '待支付',
			3 => '待发货',
			4 => '待签收',
			5 => '交易成功',
			6 => '申请退货',
			7 => '拒绝退货',
			8 => '退货中',
			9 => '退货成功',
			10 => '已申请退款', 
			11 => '退款处理中',
			12 => '退款成功',
	);
	
	private $giftsStatus = array(
		0 => '已下单',
		1 => '请分享',
		2 => '待发货',
	);
	
	private $coquetryStatus = array(
		0 => '已留言',
		1 => '分享并找朋友代付',
		2 => '代付成功',
		3 => '代付失败',
	);
	
	static $GIFTS_TYPES = array(
			1 => "送礼订单",
			2 => "收礼订单",
	);
	
	// 可查询的订单状态列表
	static $TYPES = array(
			1 => "待付款订单",
			2 => "待收货订单",
			3 => "交易成功订单",
			4 => "退款订单",
			//0 => "其它订单",
	);
	
	/**
	 * 随机订单NO
	 * @param unknown $sid
	 * @return string
	 */
	public static function randOrderNo( $sid ) {
		return date ( "ymdHis" ) . str_pad ( $sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 );
	}
	
	/**
	 * 随机订单NO
	 * @param unknown $sid
	 * @return string
	 */
	public static function randRefundNo( $sid ) {
		return date ( "ymdHis" ) . str_pad ( $sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 );
	}
	
	/**
	 * 获得订单显示状态
	 * @param $status 订单状态
	 * @param $payStatus 支付状态
	 */
	public function getOrderShowStatus( $order ) {
		$status = $order['order_status'];
		$payStatus = $order['pay_status'];
		$statusText = "";
		if(isset($this->status[$status])) {
			if(!$payStatus and ($status == self::ORDER_STATUS_SHIPPING or $status == self::ORDER_STATUS_SIGN)) {
				$statusText = $this->status[$status]."(货到付款)";
			} else {
				$statusText =  $this->status[$status];
			}
		} else {
			$statusText = $this->status[0];
		}
		
		/* 购买方式下的订单状态  */
		if ( $order['buy_method'] == self::BUY_METHOD_GIFTS ) {
			$statusText = $this->getGiftsOrderShowStatus ( $order, $statusText );
		} elseif ( $order['buy_method'] == self::BUY_METHOD_COQUETRY ) {
			$statusText = $this->getCoquetryOrderShowStatus ( $order, $statusText );
		}		
		return $statusText;
	}
	
	/**
	 * 获得订单操作(前台)
	 * @param array $order
	 * @return
	 * array(
	 * 	 'pay',
	 * 	 'sign',
	 * )
	 */
	public function getOrderOperate( $order ) {
		$status = $order['order_status'];
		$payStatus = $order['pay_status'];
		$operates = array();
		if( $order['pay_method'] != 'COD' and $status == self::ORDER_STATUS_PAY  ) {
			$operates[] = "pay";
			$operates[] = "cancel";
			if ( $order['buy_method'] == self::BUY_METHOD_COMMON ) {
				$operates[] = "startPayAnother"; // 发起代付
			}
		} elseif( $status == self::ORDER_STATUS_SHIPPING ) {
			$operates[] = "refund"; // 退款
		} elseif ( $status == self::ORDER_STATUS_SIGN ) {
			$operates[] = "sign";
		} elseif ( $status == self::ORDER_STATUS_COMPLETED ) {
			$operates[] = "rate";
		}
		/* 不同的购买方式处理 */
		if ( $order['buy_method'] == self::BUY_METHOD_GIFTS ) {
			$operates = $this->getGiftsOrderOperate( $order, $operates );
		} elseif ( $order['buy_method'] == self::BUY_METHOD_COQUETRY ) {
			$operates = $this->getCoquetryOrderOperate( $order, $operates );
		}
		return $operates;
	}
	
	/**
	 * 获得送礼订单状态
	 * @param $status 订单状态
	 * @param $payStatus 支付状态
	 */
	private function getGiftsOrderShowStatus( $order, $statusText ) {
		$status = $order['order_status'];
		if ( $status == self::ORDER_STATUS_SHIPPING ) {
			$statusText = $this->giftsStatus[$order['buy_status']];
		}
		return $statusText;
	}
	
	/**
	 * 获得订单操作(前台)
	 * @param array $order
	 * @return
	 * array(
	 * 	 'pay',
	 * 	 'sign',
	 * 	 'share',
	 * )
	 */
	private function getGiftsOrderOperate( $order, &$operates ) {
		$user = session(session('sessionKey'));
		$status = $order['order_status'];
		$buy_status = $order['buy_status'];
		if ( $status == self::ORDER_STATUS_SHIPPING ) {
			if ( $buy_status == self::ORDER_GIFTS_STATUS_SHARING ) { // 分享操作
				$operates[] = "share";
			}
		} elseif ( $status == self::ORDER_STATUS_SIGN ) {
			if ( $buy_status == self::ORDER_GIFTS_STATUS_CONSIGNEE ) {
				if ( $user['id'] == $order['to_uid'] ) {
				} else {
					($key = array_search('sign', $operates)) !== false && array_splice($operates, $key, 1);  // 非收礼方无签收操作
				}
			}
		} elseif ( $status == self::ORDER_STATUS_COMPLETED ) {
			if ( $user['id'] == $order['to_uid'] ) {
			} else {
				($key = array_search('rate', $operates)) !== false && array_splice($operates, $key, 1); // 非收礼方无评价操作
			}
		}
		return $operates;
	}
	
	/**
	 * 获得送礼订单状态
	 * @param $status 订单状态
	 * @param $payStatus 支付状态
	 */
	private function getCoquetryOrderShowStatus( $order, $statusText ) {
		$status = $order['order_status'];
		if ( $status == self::ORDER_STATUS_PAY ) {
			$statusText = $this->coquetryStatus[$order['buy_status']];
		}
		return $statusText;
	}

	
	/**
	 * 获得订单操作(前台)
	 * @param array $order
	 * @return
	 * array(
	 * 	 'share',
	 * )
	 */
	private function getCoquetryOrderOperate( $order, &$operates ) {
		$status = $order['order_status'];
		$buy_status = $order['buy_status'];
		if ( $status == self::ORDER_STATUS_PAY ) {
			if ( $buy_status == self::ORDER_COQUETRY_STATUS_SHARING ) { // 分享操作
				$this->removeValue($operates, 'pay');
				$operates[] = "payAnother";  // 代理付款
				$operates[] = "share";
			} elseif ( $buy_status == self::ORDER_COQUETRY_STATUS_SAVED ) {
				$operates[] = "payAnother";  // 代理付款
				$this->removeValue($operates, 'pay');
			}
		}
		$this->removeValue($operates, 'cancel');
		return $operates;
	}
	
	/**
	 * 获得退款详细
	 */
	public function getRefundDetails( $orderNo ) {
		$data = array();
		$refundList = M("MallRefund a")->join("__MALL_REFUND_GOODS__ b on a.id = b.refundId", "LEFT")
									->join("__MALL_ORDER_GOODS__ c on b.orderGoodsId = c.id")
									->where(array('orderNo' => $orderNo))->field("a.*,b.refundFee,c.product_name,c.product_pic,c.product_attr")->select();
		if ( $refundList ) {
			foreach ( $refundList as $v ) {
				if ( !$data[$v['id']] ) {
					$data[$v['id']] = array(
						'orderNo' => $v['orderNo'],
						'refundTotalFee' => $v['refundTotalFee'],
						'items' => array(),
					);
				}
				$data[$v['id']]['items'] = array(
					'refundFee' => $v['refundFee'],
					'productName' => $v['product_name'],
					'productPic' => $v['product_pic'],
					'productAttr' => $v['product_attr'],
				);
			}
			return $data;
		}
		return false;		
	}
	
	/**
	 * 绑定订单详细
	 * @param unknown $orderLists 查询出的订单列表
	 */
	public function bindOrderDetail( &$orderLists, $getOperate = 1 ) {
		/* 关联订单商品 */
		$dProductOrder = $this;
		$mProductGoods = M ( "MallOrderGoods" );
		foreach ( $orderLists as &$v ) {
			if( $v ) {
				/* 处理不同的购买方式 */
				$controller = "MallOrder";
				$action = "showOrder";
				if ( $v['buy_method'] == self::BUY_METHOD_GIFTS ) {
					$controller = 'MallGiftsOrder';
					$gifts = M("MallGifts gifts")->where ( "gifts.order_id = {$v['id']}" )->find();
					$v['buy_status'] = $gifts['buy_status'];
					$v['to_uid'] = $gifts['to_uid'];
				} elseif ( $v['buy_method'] == self::BUY_METHOD_COQUETRY ) {
					$coquetry = M("MallCoquetry coquetry")->where ( "coquetry.order_id = {$v['id']}" )->find();
					$v['sell'] = $coquetry['sell'];
					$v['progress'] = $coquetry['progress'];
					$v['say'] = $coquetry['say'];
					$v['buy_status'] = $coquetry['buy_status'];
					$v['remain'] = number_format(($coquetry['total'] - $v['sell']) <= 0 ? 0 : ($coquetry['total'] - $v['sell']), 2);
					$v['coquetry_id'] = $coquetry['id'];
				}
				
				/* 订单状态  */
				$v["orderStatusName"] = $dProductOrder->getOrderShowStatus ( $v );
				
				/* 订单详细页链接 */
				$v['url'] = U("Home/{$controller}/{$action}", 'id='.$v['id'].'&'.'sid='.$_REQUEST['sid']);
				
				/* 订单退款信息 */
				false !== ($refund = $this->getRefundDetails($v['order_id'])) and $v['refund'] = $refund;
				
				/* 绑定订单商品 */
				$orderGoods = $mProductGoods->where ( "order_id=%d", $v ['id'] )->select ();
				foreach ( $orderGoods as &$v0 ) {
					$v ['orderItems'] [$v0 ['product_id']] or $v ['orderItems'] [$v0 ['product_id']] = array (
							'productId' => $v0 ['product_id'],
							'productName' => $v0 ['product_name'],
							'items' => array (),
					);
					$v ['orderItems'] [$v0 ['product_id']] ['items'] [] = array (
							'orderGoodsId' => $v0 ['id'],
							'productPic' => $v0 ['product_pic'],
							'productNumber' => $v0 ['product_number'],
							'productPrice' => $v0 ['product_price'],
							'productAttr' => $v0 ['product_attr'],
							'rate_status' => $v0 ['rate_status'],
					);
				}
				
				/* 订单买家操作 */
				$getOperate and $v['operates'] = $this->getOrderOperate( $v );
			}
		}
	}
	
	/**
	 * 获得一个订单
	 * @param int $id 订单id 
	 * @param int $uid 用户id 可空
	 * @param int $cid 客户id 可空
	 * @return unknown
	 */
	public function getOrder($id, $uid = 0, $cid = 0) {
		$condition = array(
						"orders.id" => $id,
					 );
		$uid and $condition['uid'] = $uid;
		$cid and $condition['cid'] = $cid;
		$order = M ( "MallOrder orders" )->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
											->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
											->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
											->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
											->where ($condition)->find () and
		$orders = array (
						&$order
				  ) and $this->bindOrderDetail ( $orders );
		return $order;
	}
	
	/**
	 * 计算一组用户的分成
	 * @param array $uids
	 * array(
	 * 	1,2,3
	 * )
	 * @param array $percent 74:10:5
	 * array(
	 * 	74,10,5
	 * )
	 * @param number $bonus 1000.00
	 * @return multitype:string
	 * array(
	 * 		1 => 550.00,
	 * 		2 => 30.00,
	 *		3 => 12.00,
	 * )
	 */
	public static function calcSimpleRewardBonus($uids, $percent, $bonus) {
		$bon = array();
		if ( $uids ) {
			for( $i=0; $i<count($uids); $i++ ) { // 计算每个用户的分成
				$bon[$uids[$i]] = number_format(($percent[$i]/100)*$bonus, 2);
			}
		}
		return $bon;
	}
	
	/**
	 * 计算基本佣金
	 * @param $orderGoodsList
	 * array(
	 * 	 array(
	 * 		'id' => 0,
	 * 		'reward_price' => '',
	 * 		'product_number' => '',
	 * 		'reward_uids' => '1,2,3',
	 * 		'reward_percent' => '20:10:5',
	 * 	 )
	 * )
	 * @return
	 * array(
	 * 	 'orderBonus' => 298.00, // 订单总佣金
	 * 	 'totalUser' => array(
	 *		'32' => 20.00,
	 *		'38' => 10.00,
	 * 	  )
	 * )
	 */
	public static function calcRewardBonus( $orderGoodsList ) {
		$totalUser = array();  // 当前订单每个参与用户的返拥结果
		$orderBonus = 0; // 订单总佣金(非实际发放佣金)
		foreach ( $orderGoodsList as $v) {
			$total = $v['reward_price']*$v['product_number']; // 商品总佣金
			/*分配佣金*/
			if ( $v['reward_uids'] ) {
				$uids = explode(',', $v['reward_uids']);
				$percent = explode(':', $v['reward_percent']);
				$userBonus = self::calcSimpleRewardBonus($uids, $percent, $total);
				for( $i=0; $i<count($uids); $i++ ) { // 计算每个用户的分成
					$totalUser[$uids[$i]] = $totalUser[$uids[$i]]*1 + $userBonus[$uids[$i]]*1;
				}
			}
			/*订单总佣金*/
			$orderBonus += $total;
		}
		return array(
			'orderBonus' => $orderBonus,
			'totalUser' => $totalUser,
		);
	}
	
	/**
	 * 分配特约经销商佣金
	 * @param $orderGoodsList
	 * array(
	 * 	 array(
	 * 		'id' => 0,
	 * 		'reward_price_dealer' => '',
	 * 		'product_number' => '',
	 * 		'reward_uids_dealer' => '1,2,3',
	 * 		'reward_percent_dealer' => '20:10:5',
	 * 	 )
	 * )
	 * @return
	 * array(
	 * 	 'orderBonus' => 298.00, // 订单总佣金
	 * 	 'totalUser' => array(
	 *		'32' => 20.00,
	 *		'38' => 10.00,
	 * 	  )
	 * )
	 */
	public static function calcRewardBonusDealer( $orderGoodsList ) {
		$totalUser = array();  // 当前订单每个参与用户的返拥结果
		$orderBonus = 0; // 订单总佣金(非实际发放佣金)
		foreach ( $orderGoodsList as $v) {
			$total = $v['reward_price_dealer']*$v['product_number']; // 商品总佣金
			/*分配佣金*/
			if ( $v['reward_uids_dealer'] ) {
				$uids = explode(',', $v['reward_uids_dealer']);
				$percent = explode(':', $v['reward_percent_dealer']);
				$userBonus = self::calcSimpleRewardBonus($uids, $percent, $total);
				for( $i=0; $i<count($uids); $i++ ) {
					$totalUser[$uids[$i]] = $totalUser[$uids[$i]]*1 + $userBonus[$uids[$i]]*1;
				}
			}
			/*订单总佣金*/
			$orderBonus += $total;
		}
		return array(
			'orderBonus' => $orderBonus,
			'totalUser' => $totalUser,
		);
	}
	
	private function removeValue( &$operates, $value ) {
		$key = array_search($value, $operates);
		if ($key !== false)
			array_splice($operates, $key, 1);
	}
	
}